package main

import "fmt"

//#link: https://leetcode-cn.com/problems/contiguous-array/
func main() {
	nums := []int{0, 0, 1, 0, 0, 0, 1, 1}
	fmt.Println(findMaxLength(nums))
}

//把0当做-1，然后找和为0的最长子数组
func findMaxLength(nums []int) int {
	tempMap := make(map[int]int)
	tempMap[0] = -1
	preSum, result := 0, 0
	//计算出前缀和来
	for i, num := range nums {
		if num == 1 {
			preSum++
		} else {
			preSum--
		}
		if value, ok := tempMap[preSum]; ok {
			result = max(result, i-value)
		} else {
			tempMap[preSum] = i
		}
	}

	return result
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
